<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../static/layui/css/layui.css"  media="all">
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
</head>
<body>

<div class="demoTable">
    <div class="layui-form" style="float: left">
        <label class="layui-form-label">仓库名称</label>
        <div class="layui-inline">
            <select class="layui-select" name="houseCode" id="demoReload" lay-verify="required">
                <option value="">全部</option>
            </select>
        </div>
    </div>
    <div class="layui-form" style="float: left">
        <label class="layui-form-label">供应商名称</label>
        <div class="layui-inline">
            <select class="layui-select" name="supplierCode" id="demoReload1" lay-verify="required">
                <option value="">全部</option>
            </select>
        </div>
    </div>

    <button class="layui-btn" data-type="reload">搜索</button>
</div>
<!-- 添加的from表单 -->
<form class="layui-form" action="" id="addForm" style="display:none" lay-filter="add" enctype="multipart/form-data">

    <div class="layui-form-item">
        <label class="layui-form-label">名称</label>
        <div class="layui-input-block">
            <input type="text" id="name" name="name" lay-verify="required" autocomplete="off" placeholder="名称" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">单价</label>
        <div class="layui-input-block">
            <input type="text" id="price" name="price" lay-verify="required" autocomplete="off" placeholder="单价" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">数量</label>
        <div class="layui-input-block">
            <input type="text" id="num" name="num" lay-verify="required" autocomplete="off" placeholder="数量" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">仓库编号</label>
        <div class="layui-input-block">
            <select class="layui-select" name="houseCode" id="otype" lay-verify="required">
                <option value="">请选择</option>
            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">供应商编号</label>
        <div class="layui-input-block">
            <select class="layui-select" name="supplierCode" id="SupplierType" lay-verify="required">
                <option value="">请选择</option>
            </select>
        </div>
    </div>


    <div class="layui-form-item" id="sub">
        &nbsp;&nbsp;&nbsp;<button style="" class="layui-btn" type="button" lay-submit lay-filter="demo2" id="addsub">提交</button>
    </div>
</form>



<table class="layui-hide" id="test" lay-filter="test"></table>
<!--修改的from表单 -->
<form class="layui-form" action="" id="updataForm" style="display:none" lay-filter="updata" enctype="multipart/form-data">
    <div class="layui-form-item" style="display:none">
        <label class="layui-form-label">id</label>
        <div class="layui-input-block">
            <input type="text" id="id" name="id" lay-verify="id" autocomplete="off" placeholder="id" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">名称</label>
        <div class="layui-input-block">
            <input type="text" id="name" name="name" lay-verify="required" autocomplete="off" placeholder="名称" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">单价</label>
        <div class="layui-input-block">
            <input type="text" id="price" name="price" lay-verify="required" autocomplete="off" placeholder="单价" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">数量</label>
        <div class="layui-input-block">
            <input type="text" id="num" name="num" lay-verify="required" autocomplete="off" placeholder="数量" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">仓库编号</label>
        <div class="layui-input-block">
            <select class="layui-select" name="houseCode" id="otype1" lay-verify="required">
                <!--<option value="">请选择</option>-->
            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">供应商编号</label>
        <div class="layui-input-block">
            <select class="layui-select" name="supplierCode" id="SupplierType1" lay-verify="required">
                <!--<option value="">请选择</option>-->
            </select>
        </div>
    </div>



    <div class="layui-form-item" id="sub">
        &nbsp;&nbsp;&nbsp;<button style="" class="layui-btn" type="button" lay-submit lay-filter="demo3" id="updatasub">确认</button>
    </div>
</form>

<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button type="button" class="layui-btn layui-btn-sm" id="add" lay-event="add">添加</button>
    </div>
</script>


<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script src="../static/layui/layui.js" charset="utf-8"></script>
<!-- 注意：如果你直接复制所有代码到本地，上述js路径需要改成你本地的 -->

<script>


    layui.use('table', function(){
        var table = layui.table;
        layer.ready(function(){
            getHouseList();
            getSupplierList();
        });


        table.render({
            elem: '#test'
            ,url:'http://localhost:8080/product/pageList'
            ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: ['filter', 'exports', 'print']
            ,title: '用户数据表'
            ,cols: [
                [
                {type: 'checkbox', fixed: 'left',sort:true}
                ,{field:'id', title:'id', width:100}
                ,{field:'name', title:'商品名称', width:200}
                ,{field:'price', title:'单价', width:200}
                ,{field:'num', title:'数量', width:200}
                ,{field:'houseName', title:'仓库', width:200}
                ,{field:'supplierName', title:'供应商', width:200}
                ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:150}
                ]
            ]
            ,id: 'testReload'
            ,page: false
            ,response:{
                statusName: 'status' //规定数据状态的字段名称，默认：code
                ,dataName: 'rows' //规定数据列表的字段名称，默认：data
            }
            ,parseData: function(res){ //将原始数据解析成 table 组件所规定的数据
                return {
                    "status": res[0].status,   //解析接口状态
                    "message":res[1].message,  //解析提示文本
                    "count": 10,       //解析数据长度
                    "rows": res[3].rows.item  //解析数据列表
                };
            }
        });


        var layui$ = layui.$, active = {
            reload: function(){
                var demoReload = layui$('#demoReload');
                var demoReload1 = layui$('#demoReload1');

                //执行重载
                table.reload('testReload', {
                    page: false
                    /*{
                        curr: 1 //重新从第 1 页开始
                    }*/
                    ,where: {
                        houseCode: demoReload.val()
                        ,supplierCode: demoReload1.val()
                    }
                });
            }
        };

        layui$('.demoTable .layui-btn').on('click', function(){
            var type = layui$(this).data('type');
            active[type] ? active[type].call(this) : '';
        });




        //头工具栏事件
        table.on('toolbar(test)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'add':
                    add();
                    break;
            };
        });

        //监听行工具事件
        table.on('tool(test)', function(obj){
            var data = obj.data;
            //console.log(obj)
            if(obj.event === 'del'){
                layer.confirm('真的删除行么', function(index){
                    obj.del();
                    deleteById(data.id);
                    layer.close(index);
                });
            } else if(obj.event === 'edit'){
                form.val("updata", { //formTest 即 class="layui-form" 所在元素属性 lay-filter="" 对应的值
                    "id": data.id // "name": "value"
                    ,"name":data.name
                    ,"price":data.price
                    ,"num":data.num
                    ,"houseCode":data.houseCode
                    ,"supplierCode":data.supplierCode
                });
                updateById(data);
            }
        });

        //添加的from表单
        layui.use(['form', 'laydate'], function(){
            form = layui.form;
            form.render();

            //增加的form
            form.on('submit(demo2)', function(data){
                console.log(JSON.stringify(data.field));
                $.ajax({
                    url:'http://localhost:8080/product/saveOrUpdate',
                    method:'get',

                    data:data.field,
                    dataType:'JSON',
                    success:function(res){
                        if(res.status==0){
                            //console.log(res);
                            layer.msg("添加成功");
                            $("#addForm")[0].reset();
                            form.render();
                            //刷新页面
                            table.reload('test', {
                                url: 'http://localhost:8080/product/pageList'
                            });
                        }else{
                            layer.msg("添加失败");
                            $("#addForm")[0].reset();
                            form.render();
                        }
                    },
                    error:function (data) {
                        layer.msg("网络错误");
                        $("#addForm")[0].reset();
                        form.render();
                    }
                }) ;
                layer.close(layer_index);
            });

            //修改的form表单
            form.on('submit(demo3)', function(data){
                console.log(JSON.stringify(data.field));
                $.ajax({
                    url:'http://localhost:8080/product/saveOrUpdate',
                    method:'get',
                    data:data.field,
                    dataType:'JSON',
                    success:function(res){
                        if(res.status==0){
                            //console.log(res);
                            layer.msg("修改成功");
                            $("#updataForm")[0].reset();
                            form.render();
                            table.reload('test', {
                                url: 'http://localhost:8080/product/pageList'
                            });

                        }else{
                            layer.msg("修改成功");
                            $("#updataForm")[0].reset();
                            form.render();
                        }
                    },
                    error:function (data) {
                        layer.msg("网络错误");
                        $("#updataForm")[0].reset();
                        form.render();
                    }
                }) ;
                layer.close(layer_index);
            });

        });

        //修改
        function updateById(data){

            layer_index= layer.open({
                type: 1,  //可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                title: "修改", //数组第二项可以写任意css样式；如果你不想显示标题栏，你可以title: false
                area: ['500px', '400px'], //所打开页面大小
                content:$("#updataForm"), //内容
                //将数据显示在框上边

                //关闭操作
                cancel: function(){
                    layer.close(layer_index);
                    $("#updataForm")[0].reset();

                }
            });

        }

        function add(){
            layer_index= layer.open({
                type: 1,  //可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                title: "添加", //数组第二项可以写任意css样式；如果你不想显示标题栏，你可以title: false
                area: ['500px', '400px'], //所打开页面大小
                content:$("#addForm"), //内容
                //关闭操作
                cancel: function(){
                    layer.close(layer_index);
                    $("#addForm")[0].reset();
                    $('#demoe1').attr('src', "");
                }
            });

        }


        //删除
        function deleteById(index){

            var url = "http://localhost:8080/product/deleteById";
            $.ajax({
                type: "get", //指定提交的类型 get对应 doGet()方法，post--->doPost()犯法
                url: url,    //传输地址的URL
                data: {"id":index}, //data代表我们的数据  key -value类型的数据
                dataType:'JSON',
                async : false, //success和error代表是否返回成功，既后台给前台传输数据是否成功
                success: function (res)
                {
                    layer.msg("删除成功");
                },
                error:function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(typeof(errorThrown));
                }
            });
        }

        function getHouseList(){
            $.ajax({
                url: 'http://localhost:8080/house/list',
                dataType: 'json',
                data:{'page': 1
                    ,'limit':1000},	//查询状态为正常的所有机构类型
                type: 'post',
                success: function (data) {
                    $.each(data[3].rows.item, function (index, item) {
                        console.log(item);
                        $('#otype').append(new Option(item.houseName, item.houseCode));// 下拉菜单里添加元素
                        $('#demoReload').append(new Option(item.houseName, item.houseCode));// 下拉菜单里添加元素
                        $('#otype1').append(new Option(item.houseName, item.houseCode));// 下拉菜单里添加元素
                    });
                    layui.form.render("select");
                }
            })
        }

        function getSupplierList(){
            $.ajax({
                url: 'http://localhost:8080/supplier/list',
                dataType: 'json',
                data:{'page': 1
                    ,'limit':1000},	//查询状态为正常的所有机构类型
                type: 'post',
                success: function (data) {
                    $.each(data[3].rows.item, function (index, item) {
                        console.log(item);
                        $('#SupplierType').append(new Option(item.supplierName, item.supplierCode));// 下拉菜单里添加元素
                        $('#SupplierType1').append(new Option(item.supplierName, item.supplierCode));// 下拉菜单里添加元素
                        $('#demoReload1').append(new Option(item.supplierName, item.supplierCode));// 下拉菜单里添加元素
                    });
                    layui.form.render("select");
                }
            })
        }

        layui.use('laydate',function () {
            var laydate=layui.laydate;
            laydate.render({
                elem:'#ftime',
                type:'datetime'
            });
        });

    });




</script>

</body>
</html>